package com.zmx.piglearn.activity

import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.zmx.piglearn.MainActivity
import com.zmx.piglearn.R

class LoginActivity : BaseActivity(), View.OnClickListener {

    private lateinit var pref: SharedPreferences
    private lateinit var editor: SharedPreferences.Editor
    private lateinit var editUser: EditText
    private lateinit var editPwd: EditText
    private lateinit var btnLogin: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        pref = PreferenceManager.getDefaultSharedPreferences(this)
        bindViews()
    }

    private fun bindViews() {
        editUser = findViewById(R.id.edit_user)
        editPwd = findViewById(R.id.edit_pwd)
        btnLogin = findViewById(R.id.btn_login)
        btnLogin.setOnClickListener(this)
    }

    override fun onStart() {
        super.onStart()
        if ("" != pref.getString("user", "")) {
            editUser.setText(pref.getString("user", ""))
            editPwd.setText(pref.getString("pwd", ""))
        }
    }

    override fun onClick(v: View?) {
        val user = editUser.text.toString()
        val pwd = editPwd.text.toString()
        if (user == "123" && pwd == "123") {
            editor = pref.edit()
            editor.putString("user", user)
            editor.putString("pwd", pwd)
            editor.commit()
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            Toast.makeText(this, "哟，竟然蒙对了~", Toast.LENGTH_SHORT).show()
            finish()
        } else {
            Toast.makeText(this, "不对喔，再试试~", Toast.LENGTH_SHORT).show()
        }
    }
}